package com.hb.trade.server.center.au.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hb.core.pojo.UserConfig;
import com.hb.core.pojo.center.au.dto.*;
import com.hb.core.pojo.center.au.entity.*;
import com.hb.core.pojo.center.au.vo.AgencyBidUserVo;
import com.hb.core.pojo.enums.RoleSignEnum;
import com.hb.core.pojo.enums.RoleTypeEnum;
import com.hb.core.pojo.enums.UserStatusEnum;
import com.hb.core.pojo.parent.MPBaseController;
import com.hb.core.pojo.parent.PageResult;
import com.hb.trade.server.center.au.manager.UserManager;
import com.hb.trade.server.center.au.service.*;
import lombok.extern.slf4j.Slf4j;
import org.fzzn.core.model.enums.AuditStatusEnum;
import org.fzzn.core.model.enums.MsgEnum;
import org.fzzn.core.model.enums.UserTypeEnum;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.util.Enums;
import org.fzzn.core.util.MsgUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 系统用户表，表中用户包括两种类型，系统管理用户和招标业务用户 前端控制器
 *
 * @author zhaojk
 * @since 2021-11-29
 */
@Slf4j
@RestController
public class UserController extends MPBaseController<User, UserService> {

    protected final UserExtService userExtService;
    protected final UserBlacklistService userBlacklistService;
    protected final OrgService orgService;
    protected final UserRoleService userRoleService;
    protected final OrgDeptService orgDeptService;
    protected final UserVerifyService userVerifyService;
    protected final RoleService roleService;

    public UserController(UserService service,
                          UserExtService userExtService,
                          UserBlacklistService userBlacklistService,
                          OrgService orgService,
                          UserRoleService userRoleService,
                          RoleService roleService,
                          UserVerifyService userVerifyService,
                          OrgDeptService orgDeptService) {
        super(service);
        this.userExtService = userExtService;
        this.userBlacklistService = userBlacklistService;
        this.orgService = orgService;
        this.userRoleService = userRoleService;
        this.orgDeptService = orgDeptService;
        this.userVerifyService = userVerifyService;
        this.roleService = roleService;
    }

    /**
     * 获取所有用户信息
     *
     * @param userDTO
     * @return
     */
    @PostMapping("/user/listUsers")
    public Message<List<User>> listUsers(@RequestBody UserDTO userDTO) {
        QueryWrapper<User> wrapper = userDTO.buildWrapper();
        List<User> list = service.list(wrapper);
        return MsgUtil.success(list);
    }

    /**
     * 获取指定ID的用户信息
     * 该接口用于查询开标大厅即时通讯的好友列表
     *
     * @param ids
     * @return
     */
    @PostMapping("/user/listUserByIds")
    public Message<List<User>> listUserByIds(@RequestBody List<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return MsgUtil.msg(MsgEnum.NULL_RESULT);
        }
        List<User> list = service.listByIds(ids);
        if (CollUtil.isEmpty(list)) {
            return MsgUtil.msg(MsgEnum.NULL_RESULT);
        }
        return MsgUtil.success(list);
    }

    /**
     * 获取指定用户的中招扫码用户信息
     *
     * @param userId
     * @return
     */
    @PostMapping("/user/getZappInfo")
    public Message<ZappUserDTO> getZappInfo(@RequestParam("userId") Long userId) {
        if (userId == null) {
            return MsgUtil.msg(MsgEnum.INCORRECT_PARAM);
        }
        ZappUserDTO zappUserDTO = userVerifyService.getBackInfo(userId, ZappUserDTO.class);
        if (zappUserDTO == null) {
            return MsgUtil.msg(MsgEnum.NULL_RESULT);
        }
        return MsgUtil.success(zappUserDTO);
    }

    /**
     * 获取指定用户名的用户信息
     *
     * @param username 用户名支持手机号
     * @return
     */
    @PostMapping("/user/getByUsername")
    public Message<UserDTO> getByUsername(String username) {
        // 查询用户信息
        QueryWrapper<User> wrapper = UserDTO.wrapper();
        wrapper.select("id", "avatar", "org_id", "username", "phone", "full_name",
                "email", "password", "salt_source", "user_type", "user_status",
                "tenant_id");

        wrapper.eq("username", username)
                .last("limit 1");
        User user = service.getOne(wrapper);
        if (user == null) {
            return MsgUtil.msg(MsgEnum.NULL_RESULT);
        }
        return MsgUtil.success(user.to(UserDTO.class));
    }

    /**
     * 查询指定用户名的用户是否在黑名单里
     * 仅支持用户ID查询
     *
     * @param user
     * @return
     */
    @PostMapping("/user/existsInBlackList")
    public Message<Boolean> existsInBlackList(@RequestBody User user) {
        // 查询用户信息
        boolean exists = service.existsInBlackList(user.getId());
        return MsgUtil.success(exists);
    }

    /**
     * 获取用户列表信息，带分页
     *
     * @return
     */
    @PostMapping("/user/pageUsers")
    public Message<PageResult<UserDTO>> pageUsers(@RequestBody UserDTO userDto) {
        Page<User> pages = userDto.pages();

        // 合并角色参数
        userDto.mergeRoleIds();

        service.pageUsers(pages, userDto);
        PageResult<User> pageResult = PageResult.get(pages);
        PageResult<UserDTO> transferTo = pageResult.transferTo(UserDTO.class);

        for (UserDTO record : transferTo.getRecords()) {
            // 设置角色
            List<RoleDTO> roles = userRoleService.listRolesByUserId(record.getId());
            record.setRoles(roles);
            // 设置部门
            Long deptId = record.getDeptId();
            OrgDept orgDept = orgDeptService.getById(deptId);
            if (orgDept != null) {
                record.setOrgDept(orgDept.to(OrgDeptDTO.class));
            }
            //设置扩展用户信息(20220419, 身份证属性转移至用户主表中, 这里不再需要查询扩展信息了)
/*            UserExt userExt = userExtService.getUserExtByUserId(record.getId());
            if (userExt == null) {
                continue;
            }
            record.setUserExt(userExt.to(UserExtDTO.class));*/

            // 设置认证信息(注：此处正常逻辑应该是根据不同的登录方式，返回不同的认证信息，但是目前阶段我们只有中招扫码一种，登录时也没指定登录方式，所以先默认返回中招的认证信息)
            UserVerify userVerify = userVerifyService.findAuditPassInfoByUserIdAndVerifyType(record.getId(), 2);
            if (userVerify != null) {
                record.setVerifyType(2);
                record.setVerifyCode(userVerify.getVerifyCode());
                record.setBackInfo(userVerify.getBackInfo());
            }
        }
        return MsgUtil.success(transferTo);
    }

    /**
     * 新增一个系统用户
     *
     * @return
     */
    @PostMapping("/user/addSystemUser")
    public Message<Boolean> addSystemUser(@RequestBody UserDTO userDto) {
        // 针对用户信息做一些验证
        UserManager userManager = userDto.to(UserManager.class);
        String verifyAdd = userManager.verifyAdd();
        if (StrUtil.isNotEmpty(verifyAdd)) {
            return MsgUtil.fail(verifyAdd);
        }

        boolean save = service.addSystemUser(userManager);

        // 给用户赋予指定的角色
        boolean grantRole = userRoleService.updateUserRoles(userManager);

        if (!grantRole) {
            log.warn("用户授权角色失败");
        }

        return MsgUtil.success(save && grantRole);
    }

    /**
     * 删除一个用户
     *
     * @return
     */
    @PostMapping("/user/removeUser")
    public Message<Boolean> removeUser(@RequestBody UserDTO user) {
        // 删除验证
        UserManager userManager = user.to(UserManager.class);
        String verifyDelete = userManager.verifyDelete();
        if (StrUtil.isNotEmpty(verifyDelete)) {
            return MsgUtil.fail(verifyDelete);
        }

        boolean remove = service.removeById(userManager.getId());
        return MsgUtil.success(remove);
    }

    /**
     * 更新用户信息
     *
     * @return
     */
    @PostMapping("/user/updateUser")
    public Message<Boolean> updateUser(@RequestBody UserDTO userDto) {
        // 针对用户信息做一些验证
        UserManager userManager = userDto.to(UserManager.class);
        String verifyUpdate = userManager.verifyUpdate();
        if (StrUtil.isNotEmpty(verifyUpdate)) {
            return MsgUtil.fail(verifyUpdate);
        }

        // 修改用户信息
        boolean update = saveOrUpdate(userManager);

        // 如果传递了角色参数, 修改角色
        if (CollUtil.isNotEmpty(userDto.getRoleIds())) {
            // 更新用户角色
            userRoleService.updateUserRoles(userDto);
        }

        // 更新用户扩展信息
        UserExtDTO userExt = userManager.getUserExt();
        if (userExt != null) {
            userExt.setUserId(userManager.getId());
            boolean result = userExtService.updateByUserId(userExt);
            if (result) {
                log.info("更新了用户[{}]的扩展信息", userDto.getUsername());
            }
        }
        return MsgUtil.success(update);
    }

    /**
     * 根据用户id查询用户对象
     *
     * @return id
     */
    @PostMapping("/user/getByUserId")
    public Message<User> getByUserId(Long userId) {
        if (userId == null) {
            return MsgUtil.msg(MsgEnum.NULL_RESULT);
        }
        User user = service.getById(userId);
        if (user == null) {
            return MsgUtil.msg(MsgEnum.NULL_RESULT);
        }
        return MsgUtil.success(user);
    }

    /**
     * 根据id集合查询用户对象集合
     *
     * @param idList
     * @return List<User>
     * @author yuezheng
     * @date 2022/4/16 4:39 PM
     */
    @PostMapping("/user/getByUserIdList")
    public Message<List<User>> getByUserIdList(@RequestBody List<Long> idList) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(User::getId, idList);
        List<User> list = this.service.list(queryWrapper);
        return MsgUtil.success(list);
    }

    /**
     * 重置用户密码
     *
     * @return
     */
    @PostMapping("/user/resetUserPass")
    public Message<Boolean> resetUserPass(@RequestBody UserDTO userDto) {
        Long userId = userDto.getId();
        if (userId == null) {
            return MsgUtil.fail("用户ID不能为空");
        }

        // 超级管理员密码只能本人修改
        UserManager userManager = userDto.to(UserManager.class);
        if (userManager.isAdmin()) {
            return MsgUtil.msg(MsgEnum.ADMIN_ERROR);
        }

        User user = service.getById(userId);
        user.setPassword(userDto.getPassword());
        return MsgUtil.success(service.updateById(user));
    }

    /**
     * 拉入黑名单
     *
     * @return
     */
    @PostMapping("/user/pushToBlackList")
    public Message<Boolean> pushToBlackList(@RequestBody UserBlacklistDTO userBlack) {
        Long userId = userBlack.getUserId();
        if (userId == null && userBlack.getOrgId() == null) {
            return MsgUtil.msg(MsgEnum.INCORRECT_PARAM);
        }
        String reasonText = userBlack.getReasonText();
        if (StrUtil.isEmpty(reasonText)) {
            return MsgUtil.fail("拉黑原因不能为空");
        }

        boolean push = userBlacklistService.pushToBlackList(userBlack);
        return MsgUtil.success(push);
    }

    /**
     * 拉出黑名单
     *
     * @return
     */
    @PostMapping("/user/pullOutOfBlackList")
    public Message<Boolean> pullOutOfBlackList(@RequestBody UserBlacklistDTO userBlack) {
        Long userId = userBlack.getUserId();
        if (userId == null && userBlack.getOrgId() == null) {
            return MsgUtil.msg(MsgEnum.INCORRECT_PARAM);
        }

        boolean push = userBlacklistService.pullOutOfBlackList(userBlack);
        return MsgUtil.success(push);
    }

    /**
     * 保存中招APP的用户以及企业信息
     *
     * @return
     * @see com.hb.core.pojo.enums.RoleSignEnum
     */
    @Transactional
    @PostMapping("/user/saveZappUser")
    public Message<Boolean> saveZappUser(@RequestBody ZappUserDTO zappUser) {
        Integer roleSign = zappUser.getRoleSign();
        if (roleSign == null) {
            return MsgUtil.fail("必须指定用户的业务角色");
        }
        // 保存企业信息
        OrgDTO org = zappUser.getOrg();
        if (org == null) {
            return MsgUtil.fail("请使用企业身份登录");
        }

        // 判断企业是否存在
        Org exists = orgService.exists(org);
        if (exists != null) {
            exists.to(org);
        } else {
            org.buildBaseData(1);
            orgService.save(org);
        }
        // 查询该企业下的用户数
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getOrgId, org.getId());
        Long userCount = service.count(queryWrapper);
        // 判断用户是否存在
        UserDTO user = zappUser.getUser();
        User rawUser = service.exists(user);

        // 是否需要添加企业管理员角色
        boolean needOrgManager = false;

        if (rawUser == null) {
            // 不存在新增用户,如果该企业下没有用户则赋予企业管理员角色
            user.setOrgId(org.getId());
            if (userCount.equals(0L)) {
                // 2 管理员
                user.setUserType(UserTypeEnum.ORG_ADMIN.getCode());
                needOrgManager = true;
            } else {
                //3  普通用户
                user.setUserType(UserTypeEnum.NORMAL_USER.getCode());
            }
            user.buildBaseData(1);

            // 新增用户验证
            UserManager userManager = user.to(UserManager.class);
            userManager.setRoleSign(roleSign);
            String verifyAdd = userManager.verifyAdd();
            if (StrUtil.isNotEmpty(verifyAdd)) {
                return MsgUtil.fail(verifyAdd);
            }

            boolean save = service.save(userManager);
            if (save) {
                // 更新用户扩展信息
                UserExtDTO userExt = userManager.getUserExt();
                userExt.setUserId(userManager.getId());
                userExtService.updateByUserId(userExt);
            }

            // 给用户赋予指定的角色
            RoleSignEnum roleSignEnum = Enums.of(RoleSignEnum.class, roleSign);
            boolean grantRole = userRoleService.grantRole(user.getId(), roleSignEnum);
            if (!grantRole) {
                log.warn("用户授权角色失败");
            }

            // 企业管理员
            if (needOrgManager) {
                userRoleService.grantOrgManager(user.getId());
            }
        }

        return MsgUtil.success(true);
    }

    @Transactional
    @PostMapping("/user/registerZappUser")
    public Message<UserDTO> registerZappUser(@RequestBody ZappUserDTO zappUser) {

        Integer roleSign = zappUser.getRoleSign();
        if (roleSign == null) {
            return MsgUtil.fail("必须指定用户的业务角色");
        }
        // 保存企业信息
        OrgDTO org = zappUser.getOrg();
        if (org == null || zappUser.getLegalName() == null) {
            return MsgUtil.fail("请输入完整企业信息");
        }
        if (Enums.equals(RoleSignEnum.BIDDER, roleSign) && zappUser.getUnifiedTransactionCode() == null) {
            return MsgUtil.fail("请使用中招扫码注册");
        }
        // 验证用户名是否存在
        QueryWrapper<User> wrapper = UserDTO.wrapper();
        wrapper.eq("username", zappUser.getUserName())
                .last("limit 1");
        User checkUser = service.getOne(wrapper);
        if (checkUser != null) {
            return MsgUtil.fail("用户名已存在");
        }

        Org exists = orgService.exists(org);

        // 总公司管理员角色
        Role role = roleService.getRoleByRoleSign(Enums.of(RoleSignEnum.class, zappUser.getRoleSign()));

        //是否允许创建用户
        boolean createFlag = false;
        if (exists == null){
            createFlag = true;
        }else{
            // 查询该企业下所有符合业务角色账户
            // 这里应该查询roleType=7(总公司管理员的用户)
            User orgUser = service.getUserByOrgIdAndRoleId(role.getId(), exists.getId());
            if (orgUser != null) {
                UserDTO resUser = new UserDTO();
                if (orgUser.getFullName() != null) {
                    resUser.setFullName(orgUser.getFullName().replaceAll("(.{1}).*", "$1***"));
                }
                if (orgUser.getPhone() != null) {
                    resUser.setPhone(orgUser.getPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1***$2"));
                }
                resUser.setUserExist(1);
                return MsgUtil.msg(MsgEnum.USERNAME_DUPLICATE.code(), "企业已存在，请联系企业管理员为您开通账号", resUser);
            }else {
                createFlag = true;
            }
        }
        if (zappUser.getUnifiedTransactionCode()!=null){
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("unifiedTransactionCode", zappUser.getUnifiedTransactionCode());
            List<User> theUser = service.list(wrapper);
            if (theUser.size()>0){
                boolean result = unifiedTransactionCodeCanUse(theUser, roleSign);
                if (!result){
                    return MsgUtil.fail("该中招已绑定其他账号");
                }

            }

        }


        // 判断企业是否存在
        if (exists != null) {
            exists.to(org);
        } else {
            org.buildBaseData(1);
            orgService.save(org);

            // 总公司添加默认数据(角色信息)
            // roleService.initData(org.getId(), 1, zappUser.getRoleSign());
        }

        // 是否需要添加企业管理员角色
        UserDTO user = zappUser.getUser();
        if (createFlag) {
            // 如果是扫码登录更新企业信息（补充法人信息等）
            if (zappUser.getUnifiedTransactionCode() != null) {
                Org orgInfo = zappUser.getOrg();
                orgInfo.setId(org.getId());
                orgInfo.buildBaseData(2);
                orgService.updateById(orgInfo);
            }
            // 不存在新增用户,如果该企业下没有用户则赋予企业管理员角色
            user.setOrgId(org.getId());
            //2  现在全是待审核
            user.setUserType(UserTypeEnum.NORMAL_USER.getCode());
            user.buildBaseData(1);

            // 新增用户验证
            Integer roleType = null;
            UserManager userManager = user.to(UserManager.class);
            // 如果有机构交易码则，认为是中招扫码或者CA验证，默认通过审核，如果是手动填写企业信息则该用户为待审核
            if (zappUser.getUnifiedTransactionCode() == null) {
                userManager.setUserStatus(UserStatusEnum.DETAILED.getCode());
                roleType = RoleTypeEnum.UN_CHECKED_AGENCY.getCode();
                role = roleService.getRoleByRoleType(Enums.of(RoleTypeEnum.class, roleType));
            }
            userManager.setRoleSign(roleSign);
            Set<Long> roleIds = userManager.getRoleIds();
            if (CollUtil.isEmpty(roleIds)){
                roleIds = CollUtil.set(false, role.getId());
                userManager.setRoleIds(roleIds);
            }
            userManager.setRoleId(role.getId());
            userManager.setUnifiedTransactionCode(zappUser.getUnifiedTransactionCode());
            String verifyAdd = userManager.verifyAdd();
            if (StrUtil.isNotEmpty(verifyAdd)) {
                return MsgUtil.fail(verifyAdd);
            }
            // 设置账号等级, 由该方法进入的帐号为一级帐号
            userManager.setAccountLevel(1);
            UserConfig userConfig = new UserConfig();
            userConfig.setCanCreateBranchCompany(2);
            userManager.setUserConfig(userConfig);

            // 保存成功之后为企业生成默认角色
            boolean save = service.save(userManager);
            if (save) {
                roleService.initData(userManager, roleSign);
            }

            if (zappUser.getUnifiedTransactionCode() != null) {
                //保存中招验证信息
                UserVerify userVerify = new UserVerify();
                userVerify.buildBaseData(1);
                userVerify.setUserId(userManager.getId());
                userVerify.setVerifyType(2);
                userVerify.setAuditStatus(1);
                userVerify.setBackInfo(user.getBackInfo());
                userVerify.setVerifyCode(zappUser.getUnifiedTransactionCode());
                userVerifyService.save(userVerify);
            }

            // 给用户赋予指定的角色
            if (roleType!=null){
                // 赋予一个待审核的角色
                boolean grantRole = userRoleService.grantUnCheckedAgency(user.getId());
                if (!grantRole) {
                    log.warn("用户授权角色失败");
                }
            } else {
                RoleSignEnum roleSignEnum = Enums.of(RoleSignEnum.class, roleSign);
                boolean grantRole = userRoleService.grantRole(user.getId(), roleSignEnum);
                if (!grantRole) {
                    log.warn("用户授权角色失败");
                }
            }

        }
        UserDTO userDTO = new UserDTO();
        userDTO.setOrgName(org.getOrgName());
        userDTO.setOrgId(org.getId());
        return MsgUtil.success(userDTO);
    }


    boolean unifiedTransactionCodeCanUse(List<User> users, Integer roleSign){
        Role role = roleService.getRoleByRoleSign(Enums.of(RoleSignEnum.class, roleSign));
        // 投标人
        if (roleSign.equals(RoleSignEnum.BIDDER.getCode())){
            boolean result = true;
            for (User user: users){
                LambdaQueryWrapper<UserRole> userRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
                userRoleLambdaQueryWrapper.eq(UserRole::getUserId, user.getId());
                userRoleLambdaQueryWrapper.eq(UserRole::getRoleId, role.getId());
                userRoleLambdaQueryWrapper.last("limit 1");
                UserRole userRole = userRoleService.getOne(userRoleLambdaQueryWrapper);
                if (userRole != null){
                    result = false;
                }
            }
            return result;
        }
        // 代理机构
        Role tenderRole = roleService.getRoleByRoleSign(Enums.of(RoleSignEnum.class, RoleSignEnum.BIDDER.getCode()));
        if (roleSign.equals(RoleSignEnum.AGENCY.getCode())){
            boolean result = true;
            for (User user: users){
                LambdaQueryWrapper<UserRole> userRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
                userRoleLambdaQueryWrapper.eq(UserRole::getUserId, user.getId());
                userRoleLambdaQueryWrapper.eq(UserRole::getRoleId, role.getId());
                userRoleLambdaQueryWrapper.last("limit 1");
                UserRole userRole = userRoleService.getOne(userRoleLambdaQueryWrapper);
                if (userRole != null && !userRole.getRoleId().equals(tenderRole.getId())){
                    result = false;
                }
            }
            return result;
        }
        return true;
    }

    /**
     * 更新用户角色
     *
     * @param user
     * @return
     */
    @PostMapping("/user/updateUserRoles")
    public Message<Boolean> updateUserRoles(@RequestBody UserDTO user) {
        Long userId = user.getId();
        if (userId == null) {
            return MsgUtil.msg(MsgEnum.INCORRECT_PARAM);
        }
        // 更新用户角色
        boolean updateUserRoles = userRoleService.updateUserRoles(user);
        return MsgUtil.success(updateUserRoles);
    }

    /**
     * Description: 核对中招扫码信息是否与当前登录人一致
     *
     * @param zaphoneNum 中招扫码信息·手机号
     * @param offerId    投标人id
     * @author: fengbin
     * @date: 2022/2/23 13:51
     * @return: java.lang.Boolean
     */
    @PostMapping("/userConfirmInfo/zappUserConfirmInfo")
    public Message<Boolean> zappUserConfirmInfo(@RequestParam("zaphoneNum") String zaphoneNum, @RequestParam("offerId") Long offerId) {
        Boolean aBoolean = service.zappUserConfirmInfo(zaphoneNum, offerId);
        return MsgUtil.success(aBoolean);
    }


    /**
     * @param agencyUserDTO:
     * @Description:分页查询用户审核列表
     * @Author: zhongdl
     * @Date:2022/3/23 13:33
     * @return: {@link Message< PageResult<   AgencyBidUserVo  >> }
     **/
    @PostMapping("/user/pageAuditUser")
    public Message<PageResult<AgencyBidUserVo>> pageAuditUser(@RequestBody AgencyUserBidDTO agencyUserDTO) {
        PageResult<UserDTO> userDTOPageResult = service.pageAuditUser(agencyUserDTO);
        PageResult<AgencyBidUserVo> voPageResult = userDTOPageResult.transferTo(AgencyBidUserVo.class);
        return MsgUtil.success(voPageResult);
    }

    /**
     * @param agencyUserDTO:
     * @Description:获得代理机构用户详情
     * @Author: zhongdl
     * @Date:2022/3/23 13:33
     * @return: {@link Message< PageResult<   AgencyBidUserVo  >> }
     **/
    @PostMapping("/agencyUser/getAgencyBidUser")
    public Message<AgencyBidUserVo> getAgencyBidUser(@RequestBody AgencyUserBidDTO agencyUserDTO) {
        AgencyBidUserVo agencyBidUserVo = new AgencyBidUserVo();
        //查询用户
        Long id = agencyUserDTO.getId();
        User user = service.getById(id);
        if (user == null) {
            return MsgUtil.success(agencyBidUserVo);
        }
        //查询认证方式
        Integer verifyType = userVerifyService.getVerifyType(id);
        agencyBidUserVo.setVerifyType(verifyType);
        //查询企业信息
        if (user.getOrgId() == null) {
            return MsgUtil.success(agencyBidUserVo);
        }
        Org org = orgService.getById(user.getOrgId());
        BeanUtil.copyProperties(org, agencyBidUserVo);
        BeanUtil.copyProperties(user, agencyBidUserVo);

        return MsgUtil.success(agencyBidUserVo);
    }

    /**
     * @param agencyUserDTO:
     * @Description:审核用户
     * @Author: zhongdl
     * @Date:2022/3/23 14:59
     * @return: {@link Message< Boolean> }
     **/
    @PostMapping("/agencyUser/examine")
    public Message<Boolean> examine(@RequestBody AgencyUserBidDTO agencyUserDTO) {
        Long userId = agencyUserDTO.getId();
        User user = service.getById(userId);

        //如果为审核通过 查询当前企业的用户审核数量
        boolean approvedFlag = Enums.equals(UserStatusEnum.APPROVED, agencyUserDTO.getUserStatus());
        int count = service.approvedCount(user.getOrgId(), userId, AuditStatusEnum.PASSED.getCode());
        if (approvedFlag && count > 0) {
            return MsgUtil.fail("当前企业已经有用户审核通过,请联系管理员添加账号");
        }
        boolean examineFlag = service.examine(agencyUserDTO.getId(), agencyUserDTO.getUserStatus(), agencyUserDTO.getReason());
        if (user == null) {
            return MsgUtil.success(examineFlag);
        }
        if (approvedFlag) {
            //删除用户的指定角色
            userRoleService.deleteRole(userId, RoleTypeEnum.UN_CHECKED_AGENCY);
            //添加代理机构角色
            userRoleService.grantRole(userId, RoleSignEnum.AGENCY);
        }

        if (user.getOrgId() == null) {
            return MsgUtil.success(examineFlag);
        }

        Org org = orgService.getById(user.getOrgId());
        if (org == null || Enums.equals(UserStatusEnum.APPROVED, org.getAuditStatus())) {
            return MsgUtil.success(examineFlag);
        }
        //更新企业的审核状态
        org.setAuditStatus(agencyUserDTO.getUserStatus());
        boolean orgFlag = orgService.updateById(org);


        return MsgUtil.success(orgFlag && examineFlag);
    }

    /**
     * 根据用身份证和角色查询用户
     *
     * @param zappUserDTO
     * @return
     */
    @PostMapping("/agencyUser/getUserByIdCardAndRoleSign")
    public User getUserByIdNumAndRoleSign(@RequestBody ZappUserDTO zappUserDTO) {
        RoleService roleService = SpringUtil.getBean(RoleService.class);
        Role role = roleService.getRoleByRoleSign(Enums.of(RoleSignEnum.class, zappUserDTO.getRoleSign()));
        User user = service.getUserByRoleAndIdNum(role.getId(), zappUserDTO.getIdCard());
        return user;
    }

    /**
     * 根据用手机号和角色查询用户
     *
     * @param forgetPasswordDTO
     * @return
     */
    @PostMapping("/agencyUser/getUserByPhoneAndRoleSign")
    public User getUserByPhoneAndRoleSign(@RequestBody ForgetPasswordDTO forgetPasswordDTO) {
        Org orgInfo = new Org();
        orgInfo.setOrgName(forgetPasswordDTO.getOrgName());
        Org org = orgService.exists(orgInfo);
        if (org == null){
            return null;
        }
        RoleService roleService = SpringUtil.getBean(RoleService.class);
        Role role = roleService.getRoleByRoleSign(Enums.of(RoleSignEnum.class, forgetPasswordDTO.getRoleSign()));

        List<Long> roleIds = new ArrayList<>();
        // 代理机构查询企业下所有的角色
        LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper.eq(Role::getOrgId, org.getId());
        roleLambdaQueryWrapper.eq(Role::getRoleSign, forgetPasswordDTO.getRoleSign());
        List<Role> roles = roleService.list(roleLambdaQueryWrapper);
        if (roles.size()>0){
            for (Role role1 : roles){
                roleIds.add(role1.getId());
            }
        }
        if (forgetPasswordDTO.getRoleSign().equals(RoleSignEnum.AGENCY.getCode())){
            Role role1 = roleService.getRoleByRoleType(Enums.of(RoleTypeEnum.class, RoleTypeEnum.UN_CHECKED_AGENCY.getCode()));
            roleIds.add(role1.getId());
        }
        roleIds.add(role.getId());


        List<User> user = service.getUserByPhoneAndRoleSign(roleIds, forgetPasswordDTO.getPhone(),null);



        if (user == null) {
//            // 只有代理机构判断是否有未审核的账号
//            if (forgetPasswordDTO.getRoleSign().equals(RoleSignEnum.AGENCY.getCode())) {
//                Role role1 = roleService.getRoleByRoleType(Enums.of(RoleTypeEnum.class, RoleTypeEnum.UN_CHECKED_AGENCY.getCode()));
//                List<User> user1 = service.getUserByPhoneAndRoleSign(role1.getId(), forgetPasswordDTO.getPhone(),null);
//                if (user1==null){
//                    return null;
//                }
//                return user1.get(0);
//            }
            return null;
        }
        return user.get(0);
    }

    /**
     * 重新审核用户，更新企业信息和用户信息
     *
     * @param reConfirmUserDTO
     * @return
     */
    @Transactional
    @PostMapping("/agencyUser/reConfirmUser")
    public Message reConfirmUser(@RequestBody ReConfirmUserDTO reConfirmUserDTO) {
        LambdaQueryWrapper<Role> roleWrapper = new LambdaQueryWrapper<>();
        roleWrapper.eq(Role::getRoleSign, 3);
        roleWrapper.last("limit 1");
        Role role = roleService.getOne(roleWrapper);
        // 首先判断用户名是否存在
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getUsername, reConfirmUserDTO.getUsername());
        userWrapper.last("limit 1");
        User user2 = service.getOne(userWrapper);
        if (user2 != null && !user2.getId().equals(reConfirmUserDTO.getId())) {
            return MsgUtil.fail("该户名已存在！");
        }


        // 首先根据判断企业是否存在
        QueryWrapper<Org> wrapper = new QueryWrapper<>();
        wrapper.eq("org_name", reConfirmUserDTO.getOrgName());
        wrapper.or().eq("credit_code", reConfirmUserDTO.getCreditCode());
//        wrapper.last("limit 1");
        List<Org> orgList = orgService.list(wrapper);



        User user = service.getById(reConfirmUserDTO.getId());
        BeanUtil.copyProperties(reConfirmUserDTO, user);
        user.setUserStatus(UserStatusEnum.DETAILED.getCode());
        // 如果返回多条记录 企业疑似被注册，请联系管理员处理
        if (orgList.size()>1){
            return MsgUtil.fail("企业信息已被注册，如需继续注册请联系 系统管理。");
        }


        // 判断企业是否存在--如果不存在则更新企业信息
        if (orgList.size()==0) {
            Org orgDTO = orgService.getById(user.getOrgId());
            orgDTO.setOrgName(reConfirmUserDTO.getOrgName());
            orgDTO.setCreditCode(reConfirmUserDTO.getCreditCode());
            orgService.updateById(orgDTO);
        } else if (orgList.get(0).getLegalName() != null) {
            Org org = orgList.get(0);
            // 如果有中招扫码更新的企业信息直接判断企业名字和企业信用代码是否匹配
            if (!org.getCreditCode().equals(reConfirmUserDTO.getCreditCode()) || !org.getOrgName().equals(reConfirmUserDTO.getOrgName())) {
                return MsgUtil.fail("请填写正确的企业信息!");
            }
            user.setOrgId(org.getId());
        } else {
            Org orgDTO = orgService.getById(user.getOrgId());
            orgDTO.setOrgName(reConfirmUserDTO.getOrgName());
            orgDTO.setCreditCode(reConfirmUserDTO.getCreditCode());
            orgService.updateById(orgDTO);
        }
        // 首先判断该企业代理机构管理员是否存在
        User oldUser = service.getUserByOrgIdAndRoleId(role.getId(), user.getOrgId());
        if (oldUser != null) {
            if (oldUser.getFullName() != null) {
                oldUser.setFullName(oldUser.getFullName().replaceAll("(.{1}).*", "$1***"));
            }
            if (oldUser.getPhone() != null) {
                oldUser.setPhone(oldUser.getPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1***$2"));
            }
            return MsgUtil.msg(2004, "该企业已有管理员账号，请联系管理员为您创建账号",oldUser);
        }

        // 更新用户信息
        service.updateById(user);


        return MsgUtil.success(true);
    }

    /**
     * 通过手机号和企业名称判断是否匹配
     *
     * @param forgetPasswordDTO
     * @return
     */
    @Deprecated
    @PostMapping("/user/getUserByPhoneAndOrgName")
    public Message<User> getUserByPhoneAndOrgName(@RequestBody ForgetPasswordDTO forgetPasswordDTO) {
        if (forgetPasswordDTO == null || forgetPasswordDTO.getOrgName() == null || forgetPasswordDTO.getPhone() == null) {
            return MsgUtil.fail(MsgEnum.INCORRECT_PARAM.msg());
        }
        if (forgetPasswordDTO.getRoleSign() == null) {
            return MsgUtil.fail(MsgEnum.INCORRECT_PARAM.msg());
        }
        Org org = new Org();
        org.setOrgName(forgetPasswordDTO.getOrgName());
        Org orgDTO = orgService.exists(org);
        if (orgDTO == null) {
            return MsgUtil.fail("该企业不存在,请输入正确的企业名！");
        }
        RoleService roleService = SpringUtil.getBean(RoleService.class);
        Role role = roleService.getRoleByRoleSign(Enums.of(RoleSignEnum.class, forgetPasswordDTO.getRoleSign()));
        List<Long> roleIds = new ArrayList<>();
        // 代理机构查询企业下所有的角色
        LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper.eq(Role::getOrgId, orgDTO.getId());
        roleLambdaQueryWrapper.eq(Role::getRoleSign, forgetPasswordDTO.getRoleSign());
        List<Role> roles = roleService.list(roleLambdaQueryWrapper);
        if (roles.size()>0){
            for (Role role1 : roles){
                roleIds.add(role1.getId());
            }
        }
        roleIds.add(role.getId());
        // 判断用户是否存在
        List<User> rawUser = service.getUserByPhoneAndRoleSign(roleIds, forgetPasswordDTO.getPhone(), org.getId());
        if (rawUser == null|| rawUser.size()==0) {
            if (forgetPasswordDTO.getRoleSign().equals(RoleSignEnum.AGENCY.getCode())) {
                Role role1 = roleService.getRoleByRoleType(Enums.of(RoleTypeEnum.class, RoleTypeEnum.UN_CHECKED_AGENCY.getCode()));
                roleIds.add(role1.getId());
                rawUser = service.getUserByPhoneAndRoleSign(roleIds, forgetPasswordDTO.getPhone(), org.getId());
            }
            if (rawUser == null|| rawUser.size()==0) {
                return MsgUtil.fail(MsgEnum.USERNAME_NOT_FOUND.msg());
            } else if (rawUser.get(0).getOrgId().equals(orgDTO.getId())) {
                return MsgUtil.success();
            } else {
                return MsgUtil.fail("公司名称与手机号不匹配");
            }
        } else if (rawUser.get(0).getOrgId().equals(orgDTO.getId())) {
            return MsgUtil.success();
        } else {
            return MsgUtil.fail("公司名称与手机号不匹配");
        }

    }

    /**
     * 验证用户名是否重复
     *
     * @param userExistsDTO
     * @return
     */
    @PostMapping("/user/checkUsername")
    public Message<UserDTO> checkUsername(@RequestBody UserExistsDTO userExistsDTO) {
        // 查询用户信息
        QueryWrapper<User> wrapper = UserDTO.wrapper();
        wrapper.select("id", "avatar", "org_id", "username", "phone", "full_name",
                "email", "password", "salt_source", "user_type", "user_status",
                "tenant_id");

        wrapper.eq("username", userExistsDTO.getUserName())
                .last("limit 1");
        User user = service.getOne(wrapper);
        if (user == null) {
            return MsgUtil.msg(MsgEnum.NULL_RESULT);
        }
        return MsgUtil.success(user.to(UserDTO.class));
    }

    /**
     * 验证用户名是否重复
     *
     * @param userDTO
     * @return
     */
    @PostMapping("/user/getUserByRoleSignAndOrgName")
    public Message<User> getUserByRoleSignAndOrgName(@RequestBody UserDTO userDTO) {
        RoleService roleService = SpringUtil.getBean(RoleService.class);
        Role role = roleService.getRoleByRoleSign(Enums.of(RoleSignEnum.class, userDTO.getRoleSign()));
        Org orgInfo = new Org();
        orgInfo.setOrgName(userDTO.getOrgName());
        orgInfo.setCreditCode(userDTO.getCreditCode());
        Org org = orgService.exists(orgInfo);
        if (org == null) {
            return MsgUtil.fail("企业未注册");
        }
        User user = service.getUserByOrgIdAndRoleId(role.getId(), org.getId());
        return MsgUtil.success(user);
    }

    /**
     * 根据企业id集合查询用户
     *
     * @param orgIdList
     * @return org.fzzn.core.model.msg.Message
     * @author yuezheng
     * @date 2022/4/23 10:12 AM
     */
    @PostMapping("/user/findUserByOrgList")
    public Message<List<User>> findUserByOrgList(@RequestBody List<String> orgIdList) {
        List<User> result = service.findUserByOrgList(orgIdList);
        return MsgUtil.success(result);
    }

    /**
     * 根据id查询投标人
     *
     * @param userList
     * @return org.fzzn.core.model.msg.Message
     * @author yuezheng
     * @date 2022/4/23 10:12 AM
     */
    @PostMapping("/user/finBidUserByUserList")
    public Message<List<User>> finBidUserByUserList(@RequestBody List<User> userList) {
        List<User> result = service.finBidUserByUserList(userList);
        return MsgUtil.success(result);
    }

    @PostMapping("/user/getUserByUnifiedTransactionCodeAndRoleSign")
    public User getUserByUnifiedTransactionCodeAndRoleSign(@RequestBody ZappUserDTO zappUserDTO){
        Org orgInfo = new Org();
        orgInfo.setOrgName(zappUserDTO.getLegalName());
        orgInfo.setCreditCode(zappUserDTO.getLegalCode());
        Org org = orgService.exists(orgInfo);
        if (org == null){
            return null;
        }
//        LambdaQueryWrapper<Org> orgLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        orgLambdaQueryWrapper.eq(Org::getParentId, org.getId());
//        List<Org> orgList = orgService.list(orgLambdaQueryWrapper);

//        RoleService roleService = SpringUtil.getBean(RoleService.class);
//        Role role = roleService.getRoleByRoleSign(Enums.of(RoleSignEnum.class, zappUserDTO.getRoleSign()));
//        List<Long> roleIds = new ArrayList<>();
//        // 代理机构查询企业下所有的角色
//        List<Long> orgIds = new ArrayList<>();
//        orgIds.add(org.getId());
//        if (orgList.size()>0){
//            orgIds.addAll(orgList.stream().map(Org -> Org.getId()).collect(Collectors.toList()));
//        }
//        LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
////        roleLambdaQueryWrapper.eq(Role::getOrgId, org.getId());
//        roleLambdaQueryWrapper.in(Role::getOrgId, orgIds);
//
//        roleLambdaQueryWrapper.eq(Role::getRoleSign, zappUserDTO.getRoleSign());
//        List<Role> roles = roleService.list(roleLambdaQueryWrapper);
//        if (roles.size()>0){
//            for (Role role1 : roles){
//                roleIds.add(role1.getId());
//            }
//        }
//        roleIds.add(role.getId());
        User user = service.getUserByUnifiedTransactionCodeAndRoleSign(zappUserDTO.getUnifiedTransactionCode(), zappUserDTO.getRoleSign());
        return user;
    }

    @PostMapping("/user/getUserByOrgAndPhoneAndRoleSign")
    public User getUserByOrgAndPhoneAndRoleSign(@RequestBody ForgetPasswordDTO forgetPasswordDTO){
        RoleService roleService = SpringUtil.getBean(RoleService.class);
        Role role = roleService.getRoleByRoleSign(Enums.of(RoleSignEnum.class, forgetPasswordDTO.getRoleSign()));
        List<Long> roleIds = new ArrayList<>();
        roleIds.add(role.getId());
        // 代理机构查询企业下所有的角色
        LambdaQueryWrapper<Role> roleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roleLambdaQueryWrapper.eq(Role::getOrgId, forgetPasswordDTO.getOrgId());
        roleLambdaQueryWrapper.eq(Role::getRoleSign, forgetPasswordDTO.getRoleSign());
        List<Role> roles = roleService.list(roleLambdaQueryWrapper);
        if (roles.size()>0){
            for (Role role1 : roles){
                roleIds.add(role1.getId());
            }
        }
        List<User> users = service.getUserByPhoneAndRoleSign(roleIds, forgetPasswordDTO.getPhone(), forgetPasswordDTO.getOrgId());
        if(users!=null && users.size()>0){
            return users.get(0);
        }
        return null;
    }

    /**
     * 获取公司下的企业管理员账号
     * @param userDTO
     * @return
     */
    @PostMapping("/user/findManagerByOrgId")
    public Message<User> findManagerByOrgId(@RequestBody UserDTO userDTO) {
        User managerUser = service.findManagerByOrgId(userDTO);
        return MsgUtil.success(managerUser);
    }
}
